package org.finegold.core.netty.core.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.finegold.core.netty.core.model.ServerRequest;
import org.finegold.core.netty.core.session.Session;
import org.finegold.core.netty.core.session.SessionImpl;
import org.finegold.core.netty.server.modules.login.cmd.LoginCmd;
import org.finegold.core.netty.server.modules.login.cmd.ModuleId;
import org.finegold.core.netty.server.modules.login.entity.Login;
import org.finegold.core.netty.server.scanner.Invoker;
import org.finegold.core.netty.server.scanner.InvokerHoler;
import org.finegold.core.tool.utils.Func;
import org.finegold.core.tool.utils.ProtostuffUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 默认的通道处理器,仅仅输出信息
 * @author songkaikai
 * @since 2021/1/21
 */
@Slf4j
public class DefaultChannelHandler extends AbstractTextInboundHandler {

    private final Logger logger = LoggerFactory.getLogger(DefaultChannelHandler.class);

    public DefaultChannelHandler(ObjectMapper objectMapper) {
        super(objectMapper);
    }

    public DefaultChannelHandler(){
        this(null);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
    	logger.info("========一个客户端已连接======={}",ctx.toString());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
		handlerMessage(new SessionImpl(ctx.channel()),msg,ctx);
    	logger.info("接收到客户端的消息");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
    	logger.info("========一个连接已断开========");
    }

	/**
	 * 心跳
	 *
	 * @param ctx
	 * @param evt
	 * @throws Exception
	 */
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			if (event.state() == IdleState.ALL_IDLE) {
				//清除超时会话
				log.info("Timeout disconnect");
				ctx.channel().close();
			}
		} else {
			super.userEventTriggered(ctx, evt);
		}
	}

	/**
	 * 消息处理
	 */
	private void handlerMessage(Session session, TextWebSocketFrame msg, ChannelHandlerContext ctx) {
		log.info("消息=====================================================");
		Object object = session.getAttachment();
		String mobile="";
		if (object != null) {
			Login login = (Login) object;
			mobile= login.getUserId();
		}
		String text = msg.text();
		String[] split = text.split("~");
		if(Func.isEmpty(text)||3!= split.length){
			log.error("消息异常:{}",text);
			return;
		}
		short module = Short.parseShort(split[0]);
		short cmd = Short.parseShort(split[1]);
		if (module == ModuleId.LOGIN && cmd == LoginCmd.HEART_BEAT) {
			// 心跳不处理
			log.info("手机号:{}发送心跳,当前时间戳:{}",mobile, System.currentTimeMillis());
		} else {
			//获取命令执行器
			Invoker invoker = InvokerHoler.getInvoker(module, cmd);
			if (invoker != null) {
				// 执行命令
				try {
					if (module == 1 && cmd == 1) {
						Login login = new Login();
						login.setUserId(split[2]);
						invoker.invoke(session, ProtostuffUtil.serialize(login),ctx.channel());
					} else {
						invoker.invoke(session, ProtostuffUtil.serialize(split[2]));
					}
				} catch (Exception e) {
					log.error("消息处理异常:{}",e);
				}
			} else {
				return;
			}
		}
	}
}
